package com.qf.cdmmybatisspringbootstarter.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@EnableConfigurationProperties(DataSourceProperties.class)
//条件注解，当项目的配置中 cdm.datasource.enable配置的值为true时，这个自动配置类才生效
@ConditionalOnProperty(name = "cdm.datasource.enable",havingValue = "true",matchIfMissing = false)
public class MyBatisAutoConfiguration {

    @Autowired
    private DataSourceProperties dataSourceProperties;


    @Bean
    public DataSource ds(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(dataSourceProperties.getDriver());
        dataSource.setUrl(dataSourceProperties.getUrl());
        dataSource.setUsername(dataSourceProperties.getUsername());
        dataSource.setPassword(dataSourceProperties.getPassword());

        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean ssfb(DataSource ds){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();

        ssfb.setDataSource(ds);

        return ssfb;
    }

//    @Bean
//    public static MapperScannerConfigurer msc(){
//        MapperScannerConfigurer msc = new MapperScannerConfigurer();
//        msc.setBasePackage(dataSourceProperties.getBasePackage());
//        return msc;
//    }

}
